<template>
  <div class="market-sentiment-view min-h-screen bg-gray-100 dark:bg-gray-800 p-4">
    <LoadingSpinner :loading="loading" message="加载市场情绪分析..." />
    
    <header class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800 dark:text-gray-100">市场情绪分析</h1>
      <div class="flex space-x-2">
        <button 
          @click="refreshData" 
          class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
          :disabled="loading"
        >
          刷新数据
        </button>
      </div>
    </header>
       <!-- 市场新闻与事件 -->
       <div class="mt-4">
      <div class="bg-white dark:bg-gray-700 rounded-lg shadow p-4">
        <h2 class="text-lg font-semibold mb-4 dark:text-gray-200">市场新闻与事件</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div v-for="(news, index) in marketNews" :key="index" class="border-b border-gray-200 dark:border-gray-600 pb-3">
            <div class="flex justify-between mb-1">
              <h3 class="font-medium dark:text-gray-200">{{ news.title }}</h3>
              <span class="text-xs text-gray-500 dark:text-gray-400">{{ formatDate(news.date) }}</span>
            </div>
            <p class="text-sm text-gray-600 dark:text-gray-400 mb-2">{{ news.summary }}</p>
            <div class="flex items-center">
              <span 
                class="text-xs px-2 py-1 rounded-full mr-2"
                :class="getNewsSentimentClass(news.sentiment)"
              >
                {{ getNewsSentimentLabel(news.sentiment) }}
              </span>
              <span class="text-xs text-gray-500 dark:text-gray-400">影响度: {{ news.impact }}/10</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="grid grid-cols-12 gap-4">
   
      <!-- 左侧 - 市场情绪分析 -->
      <div class="col-span-8">
        <MarketSentimentAnalysis />
      </div>
      
      <!-- 右侧 - 市场相关指标 -->
      <div class="col-span-4 space-y-4">
        <!-- 市场指数概览 -->
        <div class="bg-white dark:bg-gray-700 rounded-lg shadow p-4">
          <h2 class="text-lg font-semibold mb-4 dark:text-gray-200">市场指数概览</h2>
          
          <div class="space-y-4">
            <div v-for="(index, i) in marketIndices" :key="i" class="flex justify-between items-center">
              <div>
                <div class="font-medium dark:text-gray-200">{{ index.name }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ index.code }}</div>
              </div>
              <div class="text-right">
                <div class="font-medium dark:text-gray-200">{{ index.price }}</div>
                <div :class="getChangeColor(index.change)">
                  {{ index.change > 0 ? '+' : '' }}{{ index.change.toFixed(2) }}%
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 市场情绪指标 -->
        <div class="bg-white dark:bg-gray-700 rounded-lg shadow p-4">
          <h2 class="text-lg font-semibold mb-4 dark:text-gray-200">市场情绪指标</h2>
          
          <div class="space-y-3">
            <div>
              <div class="flex justify-between mb-1">
                <span class="text-sm text-gray-600 dark:text-gray-400">波动率指数 (VIX)</span>
                <span class="text-sm font-medium dark:text-gray-200">{{ volatilityIndex.toFixed(2) }}</span>
              </div>
              <div class="w-full bg-gray-200 dark:bg-gray-600 rounded-full h-2">
                <div 
                  class="bg-yellow-500 h-2 rounded-full" 
                  :style="`width: ${Math.min(volatilityIndex, 100)}%`"
                ></div>
              </div>
            </div>
            
            <div>
              <div class="flex justify-between mb-1">
                <span class="text-sm text-gray-600 dark:text-gray-400">市场广度指数</span>
                <span class="text-sm font-medium dark:text-gray-200">{{ marketBreadth.toFixed(2) }}</span>
              </div>
              <div class="w-full bg-gray-200 dark:bg-gray-600 rounded-full h-2">
                <div 
                  class="bg-blue-500 h-2 rounded-full" 
                  :style="`width: ${marketBreadth}%`"
                ></div>
              </div>
            </div>
            
            <div>
              <div class="flex justify-between mb-1">
                <span class="text-sm text-gray-600 dark:text-gray-400">交易量指数</span>
                <span class="text-sm font-medium dark:text-gray-200">{{ volumeIndex.toFixed(2) }}</span>
              </div>
              <div class="w-full bg-gray-200 dark:bg-gray-600 rounded-full h-2">
                <div 
                  class="bg-purple-500 h-2 rounded-full" 
                  :style="`width: ${volumeIndex}%`"
                ></div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 热门行业情绪 -->
        <div class="bg-white dark:bg-gray-700 rounded-lg shadow p-4">
          <h2 class="text-lg font-semibold mb-4 dark:text-gray-200">热门行业情绪</h2>
          
          <div class="space-y-3">
            <div v-for="(sector, index) in sectorSentiments" :key="index">
              <div class="flex justify-between mb-1">
                <span class="text-sm text-gray-600 dark:text-gray-400">{{ sector.name }}</span>
                <span class="text-sm font-medium" :class="getSectorSentimentColor(sector.sentiment)">
                  {{ getSectorSentimentLabel(sector.sentiment) }}
                </span>
              </div>
              <div class="w-full bg-gray-200 dark:bg-gray-600 rounded-full h-2">
                <div 
                  class="h-2 rounded-full" 
                  :class="getSectorSentimentBarColor(sector.sentiment)"
                  :style="`width: ${(sector.sentiment + 1) * 50}%`"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAITradeStore } from '../store'
import errorHandler, { ErrorType, ErrorSeverity } from '../utils/error-handler'
import LoadingSpinner from '../components/global/LoadingSpinner.vue'
import MarketSentimentAnalysis from '../components/MarketSentimentAnalysis.vue'

const store = useAITradeStore()
const loading = ref(false)

// 市场指数数据
const marketIndices = ref([
  { name: '上证指数', code: 'SSE', price: 3250.78, change: 1.25 },
  { name: '深证成指', code: 'SZSE', price: 11234.56, change: 0.87 },
  { name: '创业板指', code: 'ChiNext', price: 2345.67, change: -0.45 },
  { name: '恒生指数', code: 'HSI', price: 18765.43, change: -1.12 }
])

// 市场情绪指标
const volatilityIndex = ref(28.5)
const marketBreadth = ref(62.3)
const volumeIndex = ref(75.8)

// 行业情绪
const sectorSentiments = ref([
  { name: '科技', sentiment: 0.75 },
  { name: '金融', sentiment: 0.35 },
  { name: '医疗健康', sentiment: 0.85 },
  { name: '消费', sentiment: -0.25 },
  { name: '能源', sentiment: -0.65 }
])

// 市场新闻
const marketNews = ref([
  {
    title: '央行宣布降准0.5个百分点',
    date: new Date(2023, 10, 15),
    summary: '中国人民银行决定下调金融机构存款准备金率0.5个百分点，释放长期资金约1万亿元。',
    sentiment: 0.8,
    impact: 9
  },
  {
    title: '美联储暗示可能在年内加息',
    date: new Date(2023, 10, 14),
    summary: '美联储主席在讲话中表示，通胀压力仍然存在，不排除年内再次加息的可能性。',
    sentiment: -0.6,
    impact: 8
  },
  {
    title: '科技巨头财报超预期',
    date: new Date(2023, 10, 12),
    summary: '多家科技巨头发布第三季度财报，营收和利润均超出市场预期，带动科技股上涨。',
    sentiment: 0.7,
    impact: 7
  },
  {
    title: '国内新能源汽车销量创新高',
    date: new Date(2023, 10, 10),
    summary: '今年前三季度新能源汽车销量同比增长56%，市场渗透率首次超过30%。',
    sentiment: 0.65,
    impact: 6
  }
])

// 初始化
onMounted(async () => {
  await refreshData()
})

// 刷新数据
async function refreshData() {
  try {
    loading.value = true
    await Promise.all([
      fetchMarketIndices(),
      fetchMarketSentimentData(),
      fetchMarketNews()
    ])
  } catch (error) {
    errorHandler.handleError(error, ErrorType.API, ErrorSeverity.WARNING)
  } finally {
    loading.value = false
  }
}

// 获取市场指数数据
async function fetchMarketIndices() {
  try {
    const indices = await store.getMarketIndices()
    if (indices) {
      marketIndices.value = indices
    }
  } catch (error) {
    errorHandler.handleError(error, ErrorType.API, ErrorSeverity.WARNING)
  }
}

// 获取市场情绪数据
async function fetchMarketSentimentData() {
  try {
    const data = await store.getMarketSentimentIndicators()
    if (data) {
      volatilityIndex.value = data.volatilityIndex
      marketBreadth.value = data.marketBreadth
      volumeIndex.value = data.volumeIndex
      sectorSentiments.value = data.sectorSentiments
    }
  } catch (error) {
    errorHandler.handleError(error, ErrorType.API, ErrorSeverity.WARNING)
  }
}

// 获取市场新闻
async function fetchMarketNews() {
  try {
    const news = await store.getMarketNews()
    if (news) {
      marketNews.value = news
    }
  } catch (error) {
    errorHandler.handleError(error, ErrorType.API, ErrorSeverity.WARNING)
  }
}

// 辅助函数
function getChangeColor(change) {
  if (change > 0) return 'text-green-600 dark:text-green-400'
  if (change < 0) return 'text-red-600 dark:text-red-400'
  return 'text-gray-600 dark:text-gray-400'
}

function getSectorSentimentColor(sentiment) {
  if (sentiment > 0.5) return 'text-green-600 dark:text-green-400'
  if (sentiment > 0) return 'text-green-500 dark:text-green-300'
  if (sentiment > -0.5) return 'text-red-500 dark:text-red-300'
  return 'text-red-600 dark:text-red-400'
}

function getSectorSentimentLabel(sentiment) {
  if (sentiment > 0.7) return '非常乐观'
  if (sentiment > 0.3) return '乐观'
  if (sentiment > -0.3) return '中性'
  if (sentiment > -0.7) return '悲观'
  return '非常悲观'
}

function getSectorSentimentBarColor(sentiment) {
  if (sentiment > 0.5) return 'bg-green-600'
  if (sentiment > 0) return 'bg-green-400'
  if (sentiment > -0.5) return 'bg-red-400'
  return 'bg-red-600'
}

function getNewsSentimentClass(sentiment) {
  if (sentiment > 0.5) return 'bg-green-200 dark:bg-green-700 text-green-800 dark:text-green-200'
  if (sentiment > 0) return 'bg-green-100 dark:bg-green-800 text-green-800 dark:text-green-200'
  if (sentiment > -0.5) return 'bg-red-100 dark:bg-red-800 text-red-800 dark:text-red-200'
  return 'bg-red-200 dark:bg-red-700 text-red-800 dark:text-red-200'
}

function getNewsSentimentLabel(sentiment) {
  if (sentiment > 0.5) return '强烈利好'
  if (sentiment > 0) return '利好'
  if (sentiment > -0.5) return '利空'
  return '强烈利空'
}

function formatDate(date) {
  if (!date) return ''
  if (typeof date === 'string') {
    date = new Date(date)
  }
  return date.toLocaleDateString('zh-CN')
}
</script>